package com.ruoze.bdp.controller;

import com.ruoze.bdp.commons.ResponseDto;
import com.ruoze.bdp.entity.TableStructVo;
import com.ruoze.bdp.service.MetaService;
import com.ruoze.bdp.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RequestMapping("/meta")
@RestController
public class MetaController {

    @Autowired
    private MetaService metaService;

    @GetMapping("/databases")
    public ResponseDto getMetaDatabases(@RequestParam Long id) {
        List<String> databases = metaService.getMetaDatabases(id);
        return databases != null ? ResponseUtil.successData(databases) : ResponseUtil.fail("获取源数据库名失败");
    }

    @GetMapping("/tables")
    public ResponseDto getMetaTables(@RequestParam Long id, @RequestParam String database) {
        List<String> tables = metaService.getMetaTables(id, database);
        return tables != null ? ResponseUtil.successData(tables) : ResponseUtil.fail("获取源数据表名失败");
    }

    @GetMapping("/columns")
    public ResponseDto getMetaColumns(@RequestParam Long id,
                                      @RequestParam String database, @RequestParam String table) {
        List<Map<String, String>> columns = metaService.getMetaColumns(id, database, table);
        return columns != null ? ResponseUtil.successData(columns) : ResponseUtil.fail("获取源数据字段失败");
    }

    @PostMapping("/database")
    public ResponseDto createDatabase(@RequestParam Long id, @RequestParam String name) {
        return metaService.createDatabase(id, name.trim().toLowerCase())? ResponseUtil.successData("创建数据库成功") : ResponseUtil.fail("创建数据库失败");
    }

    @PostMapping("/table")
    public ResponseDto createTable(@RequestBody TableStructVo tableVo) {
        return metaService.createTable(tableVo)? ResponseUtil.successData("创建表成功") : ResponseUtil.fail("创建表失败");
    }
}
